<template>
  <div class="guide-management-page">
    <div class="page-header mb-6">
      <div class="flex items-center justify-between">
        <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
          导游管理
        </h2>
        <div class="flex items-center space-x-2">
          <el-button type="primary" @click="handleAddGuide">
            <el-icon class="mr-1"><Plus /></el-icon>添加导游
          </el-button>
          <el-button @click="handleExport">
            <el-icon class="mr-1"><Download /></el-icon>导出数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm mb-6">
      <div class="flex flex-wrap gap-4 mb-4">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索导游姓名/ID/手机号"
          class="!w-64"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="searchForm.status"
          placeholder="认证状态"
          clearable
          class="!w-32"
        >
          <el-option label="全部" value="" />
          <el-option label="已认证" value="verified" />
          <el-option label="未认证" value="unverified" />
          <el-option label="审核中" value="pending" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>

        <el-select
          v-model="searchForm.language"
          placeholder="导游语言"
          clearable
          class="!w-32"
        >
          <el-option label="全部" value="" />
          <el-option label="中文" value="chinese" />
          <el-option label="英语" value="english" />
          <el-option label="粤语" value="cantonese" />
        </el-select>

        <el-select
          v-model="searchForm.specialty"
          placeholder="专长领域"
          clearable
          class="!w-32"
        >
          <el-option label="全部" value="" />
          <el-option label="历史文化" value="history" />
          <el-option label="自然风光" value="nature" />
          <el-option label="美食文化" value="food" />
          <el-option label="民俗风情" value="folk" />
          <el-option label="摄影指导" value="photography" />
        </el-select>

        <el-select
          v-model="searchForm.experience"
          placeholder="从业经验"
          clearable
          class="!w-32"
        >
          <el-option label="全部" value="" />
          <el-option label="3年以下" value="0-3" />
          <el-option label="3-5年" value="3-5" />
          <el-option label="5年以上" value="5+" />
        </el-select>

        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 导游列表 -->
    <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm">
      <el-table
        v-loading="loading"
        :data="guideList"
        border
        style="width: 100%"
        row-key="id"
      >
        <el-table-column label="导游信息" min-width="250">
          <template #default="{ row }">
            <div class="flex items-center space-x-3">
              <el-avatar :size="50" :src="row.avatar" />
              <div>
                <div class="flex items-center">
                  <span class="font-medium text-gray-900 dark:text-white">{{
                    row.name
                  }}</span>
                  <el-tag
                    v-if="row.status === 'verified'"
                    type="success"
                    size="small"
                    class="ml-2"
                    >已认证</el-tag
                  >
                  <el-tag
                    v-else-if="row.status === 'pending'"
                    type="warning"
                    size="small"
                    class="ml-2"
                    >审核中</el-tag
                  >
                  <el-tag
                    v-else-if="row.status === 'rejected'"
                    type="danger"
                    size="small"
                    class="ml-2"
                    >已拒绝</el-tag
                  >
                  <el-tag v-else type="info" size="small" class="ml-2"
                    >未认证</el-tag
                  >
                </div>
                <div class="text-sm text-gray-500 mt-1">ID: {{ row.id }}</div>
                <div class="text-sm text-gray-500">手机: {{ row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="基本信息" min-width="200">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm">
                <span class="text-gray-500">从业经验：</span>
                <span>{{ row.experience }}年</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">语言：</span>
                <span>{{ row.languages.join("、") }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">专长：</span>
                <span>{{ row.specialties.join("、") }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="服务数据" min-width="180">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm">
                <span class="text-gray-500">服务人数：</span>
                <span>{{ row.servedCount }}人</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">评分：</span>
                <span class="flex items-center">
                  <el-rate v-model="row.rating" disabled size="small" />
                  <span class="ml-1">{{ row.rating }}</span>
                </span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">好评率：</span>
                <span>{{ row.goodReviewRate }}%</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="收入情况" min-width="180">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm">
                <span class="text-gray-500">服务费：</span>
                <span class="font-medium text-primary-600"
                  >¥{{ row.price }}/天</span
                >
              </div>
              <div class="text-sm">
                <span class="text-gray-500">本月收入：</span>
                <span>¥{{ row.monthlyIncome }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">总收入：</span>
                <span>¥{{ row.totalIncome }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="注册时间" min-width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <div class="flex space-x-1">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button
                size="small"
                type="primary"
                @click="handleViewDetail(row)"
                >查看</el-button
              >
              <el-dropdown trigger="click">
                <el-button size="small">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleViewOrders(row)">
                      查看订单
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleViewQualification(row)">
                      查看资质
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="row.status === 'verified'"
                      @click="handleDisable(row)"
                    >
                      禁用账号
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="
                        row.status === 'unverified' || row.status === 'rejected'
                      "
                      @click="handleEnable(row)"
                    >
                      启用账号
                    </el-dropdown-item>
                    <el-dropdown-item
                      divided
                      @click="handleDelete(row)"
                      class="text-red-500"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无导游数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有添加任何导游</div>
              <div class="empty-subtext">添加导游为游客提供专业讲解服务</div>
              <el-button type="primary" @click="handleAddGuide" class="mt-4">添加第一位导游</el-button>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 导游详情模态框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="导游详情"
      width="800px"
      destroy-on-close
      append-to-body
      :before-close="handleCloseDialog"
      @open="disableBodyScroll"
      @close="enableBodyScroll"
      class="guide-detail-dialog"
    >
      <div v-if="currentGuide" class="guide-detail dialog-scrollable">
        <div class="flex items-start mb-6">
          <el-avatar :size="100" :src="currentGuide.avatar" class="mr-6" />
          <div class="flex-1">
            <div class="flex items-center">
              <h3 class="text-xl font-bold">{{ currentGuide.name }}</h3>
              <el-tag
                v-if="currentGuide.status === 'verified'"
                type="success"
                class="ml-2"
                >已认证</el-tag
              >
              <el-tag
                v-else-if="currentGuide.status === 'pending'"
                type="warning"
                class="ml-2"
                >审核中</el-tag
              >
              <el-tag
                v-else-if="currentGuide.status === 'rejected'"
                type="danger"
                class="ml-2"
                >已拒绝</el-tag
              >
              <el-tag v-else type="info" class="ml-2">未认证</el-tag>
            </div>
            <div class="mt-4 grid grid-cols-2 gap-3">
              <div class="text-sm">
                <span class="text-gray-500">导游ID：</span>
                <span>{{ currentGuide.id }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">联系电话：</span>
                <span>{{ currentGuide.phone }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">从业经验：</span>
                <span>{{ currentGuide.experience }}年</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">注册时间：</span>
                <span>{{ formatDateTime(currentGuide.createTime) }}</span>
              </div>
            </div>
          </div>
        </div>

        <el-divider content-position="left">基本信息</el-divider>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
          <div class="card">
            <h4 class="card-title">专业技能</h4>
            <div class="mb-3">
              <div class="text-sm text-gray-500 mb-1">语言能力：</div>
              <div class="flex flex-wrap gap-2">
                <el-tag
                  v-for="lang in currentGuide.languages"
                  :key="lang"
                  size="small"
                >
                  {{ lang }}
                </el-tag>
              </div>
            </div>
            <div>
              <div class="text-sm text-gray-500 mb-1">专长领域：</div>
              <div class="flex flex-wrap gap-2">
                <el-tag
                  v-for="specialty in currentGuide.specialties"
                  :key="specialty"
                  size="small"
                  type="success"
                >
                  {{ specialty }}
                </el-tag>
              </div>
            </div>
          </div>

          <div class="card">
            <h4 class="card-title">服务评价</h4>
            <div class="space-y-2">
              <div class="flex items-center">
                <span class="text-sm text-gray-500 w-16">评分：</span>
                <el-rate v-model="currentGuide.rating" disabled show-score />
              </div>
              <div class="flex items-center">
                <span class="text-sm text-gray-500 w-16">好评率：</span>
                <el-progress
                  :percentage="currentGuide.goodReviewRate"
                  :format="(val) => val + '%'"
                  :stroke-width="15"
                  status="success"
                />
              </div>
              <div class="text-sm">
                <span class="text-gray-500">累计服务：</span>
                <span>{{ currentGuide.servedCount }}人</span>
              </div>
            </div>
          </div>
        </div>

        <el-divider content-position="left">收入信息</el-divider>
        <div class="card mb-6">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
              <div class="text-primary-500 text-xl font-bold">
                ¥{{ currentGuide.price }}
              </div>
              <div class="text-sm text-gray-500 mt-1">服务费(元/天)</div>
            </div>
            <div class="text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
              <div class="text-primary-500 text-xl font-bold">
                ¥{{ currentGuide.monthlyIncome }}
              </div>
              <div class="text-sm text-gray-500 mt-1">本月收入</div>
            </div>
            <div class="text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
              <div class="text-primary-500 text-xl font-bold">
                ¥{{ currentGuide.totalIncome }}
              </div>
              <div class="text-sm text-gray-500 mt-1">累计收入</div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-center mt-6 space-x-4">
          <el-button type="primary" @click="handleEdit(currentGuide)"
            >编辑信息</el-button
          >
          <el-button @click="handleViewOrders(currentGuide)"
            >查看订单</el-button
          >
          <el-button @click="handleViewQualification(currentGuide)"
            >查看资质</el-button
          >

          <el-button
            v-if="currentGuide.status === 'verified'"
            type="warning"
            @click="handleDisable(currentGuide)"
            >禁用账号</el-button
          >

          <el-button
            v-if="
              currentGuide.status === 'unverified' ||
              currentGuide.status === 'rejected'
            "
            type="success"
            @click="handleEnable(currentGuide)"
            >启用账号</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus, Download, ArrowDown } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import * as XLSX from 'xlsx';
import axios from '@/api/axios';

const router = useRouter();
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  keyword: "",
  status: "",
  language: "",
  specialty: "",
  experience: "",
});

// 导游列表数据（作为备用的测试数据）
const mockGuideList = [
  {
    id: 1,
    name: "李明",
    avatar: "/images/guides/guide1.jpg",
    status: "verified",
    phone: "13800138000",
    experience: 5,
    languages: ["中文", "英语"],
    specialties: ["历史文化", "民俗风情"],
    servedCount: 1280,
    rating: 4.8,
    goodReviewRate: 98,
    price: 380,
    monthlyIncome: 7600,
    totalIncome: 48600,
    createTime: "2023-06-15 10:30:00",
  },
  {
    id: 2,
    name: "张华",
    avatar: "/images/guides/guide2.jpg",
    status: "verified",
    phone: "13900139000",
    experience: 8,
    languages: ["中文", "粤语"],
    specialties: ["美食文化", "摄影指导"],
    servedCount: 1560,
    rating: 4.9,
    goodReviewRate: 99,
    price: 450,
    monthlyIncome: 9000,
    totalIncome: 72000,
    createTime: "2023-04-20 14:15:00",
  },
  {
    id: 3,
    name: "王丽",
    avatar: "/images/guides/guide3.jpg",
    status: "pending",
    phone: "13700137000",
    experience: 3,
    languages: ["中文", "英语"],
    specialties: ["自然风光", "户外探险"],
    servedCount: 520,
    rating: 4.7,
    goodReviewRate: 95,
    price: 320,
    monthlyIncome: 3200,
    totalIncome: 16600,
    createTime: "2023-09-10 09:45:00",
  },
];

const guideList = ref([]);

// 格式化日期时间
const formatDateTime = (date) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 获取导游列表
const getGuideList = async () => {
  loading.value = true;
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm
    };
    
    const response = await axios.get('/admin/guides', { params });
    
    if (response && response.code === 200 && response.data) {
      guideList.value = response.data.list || [];
      total.value = response.data.total || 0;
    } else {
      // 如果API调用失败或返回空数据，使用测试数据
      guideList.value = mockGuideList;
      total.value = mockGuideList.length;
    }
  } catch (error) {
    console.error("获取导游列表失败:", error);
    ElMessage.error("获取导游列表失败，使用测试数据");
    guideList.value = mockGuideList;
    total.value = mockGuideList.length;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  page.value = 1;
  getGuideList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  page.value = 1;
  getGuideList();
};

// 添加导游
const handleAddGuide = () => {
  router.push("/admin/guides/edit/new");
};

// 编辑导游
const handleEdit = (row) => {
  router.push(`/admin/guides/edit/${row.id}`);
};

// 查看导游详情
const handleViewDetail = (row) => {
  currentGuide.value = row;
  detailDialogVisible.value = true;
};

// 查看导游订单
const handleViewOrders = (row) => {
  router.push({
    path: "/admin/guides/orders",
    query: { guideId: row.id },
  });
};

// 查看导游资质
const handleViewQualification = (row) => {
  router.push({
    path: "/admin/guides/qualification",
    query: { guideId: row.id },
  });
};

// 禁用导游账号
const handleDisable = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要禁用导游 ${row.name} 的账号吗？禁用后该导游将无法接单。`,
      "禁用账号",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    try {
      await axios.put(`/admin/guides/${row.id}/disable`);
      ElMessage.success("导游账号已禁用");
      getGuideList();
    } catch (error) {
      console.error("禁用导游账号失败:", error);
      ElMessage.error("禁用导游账号失败");
    }
  } catch (error) {
    if (error === "cancel") return;
  }
};

// 启用导游账号
const handleEnable = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要启用导游 ${row.name} 的账号吗？`,
      "启用账号",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      },
    );

    try {
      await axios.put(`/admin/guides/${row.id}/enable`);
      ElMessage.success("导游账号已启用");
      getGuideList();
    } catch (error) {
      console.error("启用导游账号失败:", error);
      ElMessage.error("启用导游账号失败");
    }
  } catch (error) {
    if (error === "cancel") return;
  }
};

// 删除导游
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除导游 ${row.name} 吗？此操作不可恢复。`,
      "删除导游",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      },
    );

    try {
      await axios.delete(`/admin/guides/${row.id}`);
      ElMessage.success("导游已删除");
      getGuideList();
    } catch (error) {
      console.error("删除导游失败:", error);
      ElMessage.error("删除导游失败");
    }
  } catch (error) {
    if (error === "cancel") return;
  }
};

// 导出数据
const handleExport = () => {
  // 准备导出数据
  const exportData = guideList.value.map(guide => ({
    导游ID: guide.id,
    导游姓名: guide.name,
    手机号: guide.phone,
    认证状态: guide.status === 'verified' ? '已认证' : 
              guide.status === 'pending' ? '审核中' : 
              guide.status === 'rejected' ? '已拒绝' : '未认证',
    从业经验: `${guide.experience}年`,
    语言能力: guide.languages.join('、'),
    专长领域: guide.specialties.join('、'),
    服务人数: guide.servedCount,
    评分: guide.rating,
    好评率: `${guide.goodReviewRate}%`,
    服务费: `¥${guide.price}/天`,
    本月收入: `¥${guide.monthlyIncome}`,
    总收入: `¥${guide.totalIncome}`,
    注册时间: formatDateTime(guide.createTime)
  }));

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, '导游管理');
  
  // 导出Excel文件
  XLSX.writeFile(workbook, `导游管理_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`);
  
  ElMessage.success("导游数据导出成功");
};

// 处理分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  getGuideList();
};

// 处理页码改变
const handleCurrentChange = (val) => {
  page.value = val;
  getGuideList();
};

// 详情模态框相关
const detailDialogVisible = ref(false);
const currentGuide = ref(null);

// 禁用/启用页面滚动
const disableBodyScroll = () => {
  document.body.style.overflow = "hidden";
};

const enableBodyScroll = () => {
  document.body.style.overflow = "";
};

// 关闭模态框
const handleCloseDialog = () => {
  detailDialogVisible.value = false;
};

// 页面加载时获取数据
onMounted(() => {
  getGuideList();
});
</script>

<style lang="scss" scoped>
.guide-management-page {
  padding: 20px;

  :deep(.el-table) {
    --el-table-border-color: var(--el-border-color-lighter);
    --el-table-header-bg-color: var(--el-fill-color-light);

    .el-table__header th {
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    .dark & {
      --el-table-border-color: var(--el-border-color-darker);
      --el-table-header-bg-color: var(--el-bg-color-overlay);

      .el-table__header th {
        color: var(--el-text-color-primary);
      }
    }
  }

  :deep(.el-pagination) {
    --el-pagination-button-color: var(--el-text-color-primary);
    --el-pagination-button-bg-color: var(--el-fill-color-blank);

    .dark & {
      --el-pagination-button-color: var(--el-text-color-primary);
      --el-pagination-button-bg-color: var(--el-bg-color-overlay);
    }
  }

  .card {
    background-color: var(--el-bg-color-overlay);
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    border: 1px solid var(--el-border-color-lighter);

    .dark & {
      border-color: var(--el-border-color-darker);
    }
  }

  .card-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    color: var(--el-text-color-primary);

    .dark & {
      border-color: var(--el-border-color-darker);
    }
  }
}

// 添加模态框样式
:deep(.guide-detail-dialog) {
  .el-dialog__header {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: var(--el-bg-color);
    margin-right: 0;
    padding: 20px 20px 10px;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .el-dialog__body {
    padding: 0;
    max-height: calc(80vh - 120px);
    overflow-y: auto;
  }

  .dialog-scrollable {
    padding: 20px;
  }

  .el-dialog__footer {
    position: sticky;
    bottom: 0;
    z-index: 10;
    background-color: var(--el-bg-color);
    padding: 10px 20px 20px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

.empty-state {
  padding: 30px 0;
  max-height: 400px;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
